//ClientGUI.java  
//
//Copyright (C) 2008 Devon Mizelle  
//  
//This program is distributed in the hope that it will be useful,  
//but WITHOUT ANY WARRANTY; without even the implied warranty of  
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the  
//GNU General Public License for more details.  
//  
//You should have received a copy of the GNU General Public License  
//along with this program.  If not, see <http://www.gnu.org/licenses/>.

package hermes;

import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JFrame;

/**
 *
 * @author  Devon Mizelle
 */
public class ClientGUI extends javax.swing.JFrame {
    private Client client = null;
    private UserMap userMap = null;
    /** Creates new form ClientGUI */
    public ClientGUI() {
        initComponents();
        client = new Client((JFrame) this);
        String uid = "";
        if(!client.userFileExists()){
            uid = getUID();
        }
        client.init(uid);
        setVisible(true);
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        userList = new javax.swing.JList();
        refreshButton = new javax.swing.JButton();
        exitButton = new javax.swing.JButton();
        sendFileButton = new javax.swing.JButton();
        menuBar = new javax.swing.JMenuBar();
        fileMenu = new javax.swing.JMenu();
        connectMenuItem = new javax.swing.JMenuItem();
        exitMenuItem = new javax.swing.JMenuItem();
        helpMenu = new javax.swing.JMenu();
        contentsMenuItem = new javax.swing.JMenuItem();
        aboutMenuItem = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Hermes");
        setResizable(false);

        jScrollPane1.setViewportView(userList);

        refreshButton.setText("Refresh");
        refreshButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                refreshButtonActionPerformed(evt);
            }
        });

        exitButton.setText("Exit");
        exitButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitButtonActionPerformed(evt);
            }
        });

        sendFileButton.setText("Send File");
        sendFileButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sendFileButtonActionPerformed(evt);
            }
        });

        fileMenu.setText("File");

        connectMenuItem.setText("Connect");
        connectMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                connectMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(connectMenuItem);

        exitMenuItem.setText("Exit");
        exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        helpMenu.setText("Help");

        contentsMenuItem.setText("Contents");
        helpMenu.add(contentsMenuItem);

        aboutMenuItem.setText("About");
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        setJMenuBar(menuBar);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(12, 12, 12)
                                .addComponent(sendFileButton))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(25, 25, 25)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(exitButton)
                            .addComponent(refreshButton))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 239, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(sendFileButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(refreshButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(exitButton))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    
    private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitMenuItemActionPerformed
        System.exit(0);
    }//GEN-LAST:event_exitMenuItemActionPerformed

    private void exitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitButtonActionPerformed
        System.exit(0);
    }//GEN-LAST:event_exitButtonActionPerformed

    private void connectMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_connectMenuItemActionPerformed
           try{
                String response = javax.swing.JOptionPane.showInputDialog(null,
                    "Please enter connection information.\nFormat: xxx.xxx.xxx.xxx:port",
                    "Connection Information",
                    javax.swing.JOptionPane.QUESTION_MESSAGE);
                String[] responses = response.split("[:]");
                connect(responses[0], responses[1]);
           }
           catch(NullPointerException npe){
               //If the user enters nothing for connection.
               //We want the clientGUI to do nothing.
               
           }
           catch(Exception e){
               showException(e);
           }
}//GEN-LAST:event_connectMenuItemActionPerformed

    private void refreshButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refreshButtonActionPerformed
        try{userMap = client.getNewUserMap();}catch(Exception e){e.printStackTrace();}// showException(e);}
        String[] ids = new String[userMap.getSize()];
        userMap.keySet().toArray(ids);
        userList.setListData(ids);
    }//GEN-LAST:event_refreshButtonActionPerformed

    private void sendFileButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sendFileButtonActionPerformed
        JFileChooser fc = new JFileChooser();
        fc.showOpenDialog(this);
        File selected = fc.getSelectedFile();
        
        String name = (String) userList.getSelectedValue();
        String ip = (String) client.userMap.get((String)userList.getSelectedValue()).get("ip");
        SendingDialog sd = null;
        try{sd = new SendingDialog(this, true, name,
                ip, selected.getAbsolutePath());}
        catch(NullPointerException e){
            showException(new Exception("You did not choose a file!"));
            
        }
        FileWrap fw = new FileWrap(selected.getAbsolutePath());
        try{client.sendFile(name, ip, selected.getAbsolutePath(), fw);}
        catch(Exception e){showException(e);}
        sd.setVisible(true);
    }//GEN-LAST:event_sendFileButtonActionPerformed
    
    public void connect(String hostname, String port){
        try{
            client.connect(hostname, port);
        }
        catch(Exception e){
            showException(e);

        }
    }
    
    public void showException(Exception e){
        e.printStackTrace();
        javax.swing.JOptionPane.showMessageDialog((java.awt.Frame) this,
                    e.toString(),
                    "Exception Caught!",
                    javax.swing.JOptionPane.ERROR_MESSAGE);
    }
    
    public String getUID(){
        return javax.swing.JOptionPane.showInputDialog((java.awt.Frame) this,
                "Please enter in a desired UserID",
                "UserID Creation",
                javax.swing.JOptionPane.QUESTION_MESSAGE);
    }
    /**
     * 
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ClientGUI().setVisible(true);
            }
        });
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem aboutMenuItem;
    private javax.swing.JMenuItem connectMenuItem;
    private javax.swing.JMenuItem contentsMenuItem;
    private javax.swing.JButton exitButton;
    private javax.swing.JMenuItem exitMenuItem;
    private javax.swing.JMenu fileMenu;
    private javax.swing.JMenu helpMenu;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JButton refreshButton;
    private javax.swing.JButton sendFileButton;
    private javax.swing.JList userList;
    // End of variables declaration//GEN-END:variables
    
}
